from http import cookies
import imaplib
import email
from email.header import decode_header
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 规避被检测
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from lxml import etree
from flask import Flask, jsonify, request
from config import configKEY
import time
def getEmailCreat():
    # QQ邮箱IMAP服务器地址
    imap_url = 'imap.qq.com'
    # 你的QQ邮箱账号和授权码
    username = '573561243@qq.com'
    password = configKEY()
    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL(imap_url)
    mail.login(username, password)
    # 选择邮箱中的"INBOX"文件夹
    mail.select("inbox")
    # 搜索所有邮件
    status, messages = mail.search(None, 'ALL')
    url_zhilian = ''

    # 检查是否有邮件
    if messages[0]:
        # 获取最新一封邮件的ID（假设邮件ID是按顺序排列的）
        latest_email_id = messages[0].split()[-1]
        # 获取邮件内容
        status, data = mail.fetch(latest_email_id, '(RFC822)')
        for response_part in data:
            if isinstance(response_part, tuple):
                # 解析邮件内容
                msg = email.message_from_bytes(response_part[1])

                # 邮件主题
                subject, encoding = decode_header(msg["Subject"])[0]
                if isinstance(subject, bytes):
                    subject = subject.decode(encoding or "utf-8")
                print('邮件主题:', subject)

                # 邮件发件人
                from_, encoding = decode_header(msg.get("From"))[0]
                if isinstance(from_, bytes):
                    from_ = from_.decode(encoding or "utf-8")
                print('邮件发件人:', from_)

                # 邮件正文
                body = ''
                if msg.is_multipart():
                    for part in msg.walk():
                        content_type = part.get_content_type()
                        content_disposition = str(part.get("Content-Disposition"))
                        try:
                            # 获取邮件正文（只处理text/plain且不是附件的部分）
                            if content_type == "text/html" and "attachment" not in content_disposition:
                                body = part.get_payload(decode=True).decode()
                                break  # 假设我们只关心第一个text/plain部分
                        except:
                            pass
                else:
                    body = msg.get_payload(decode=True).decode()
                # 将邮件正文写入文件（注意：这将覆盖文件内容）
                with open('python爬虫学习/scrapy爬虫框架/scrapyPro/scrapyPro/spiders/email.html', 'w', encoding='utf-8') as fp:
                    fp.write(body)
                soup = BeautifulSoup(body, 'lxml')
                a_tags = soup.find_all('a')
                for a_tag in a_tags:
                    if a_tag.get_text() == "去回复 >":
                        href = a_tag.get('href')
                        if href:  # 确保href属性存在
                            url_zhilian = href
                        print(href)
                chrome_options = Options()
                # 启用无头模式
                chrome_options.add_argument("--headless")
                # 启用有头模式
                # chrome_options.add_argument('--disable-gpu')
                chrome_options.add_argument(
                    "user-data-dir=./profile")  # 指定浏览器配置文件的路径
                chrome = webdriver.Chrome(options=chrome_options)
                chrome.get(url_zhilian)
                cookies = chrome.get_cookies()
                def gozhilian():
                    search_box = chrome.find_element(
                        By.XPATH, "/html/body/div/div/div[1]/div[1]/section/main/div[2]/div[2]/div[1]/div/div/a[2]/div")
                    search_box.click()
                    loginInput = chrome.find_element(
                        By.XPATH, "/html/body/div/div/div[1]/div[1]/section/main/div[2]/div[2]/div[2]/div/div/form/div[1]/div/div/div/input")
                    loginInput.send_keys("lzkjksyx819252")
                    passwordInput = chrome.find_element(
                        By.XPATH, "/html/body/div/div/div[1]/div[1]/section/main/div[2]/div[2]/div[2]/div/div/form/div[2]/div/div/div/input")
                    passwordInput.send_keys("ldx12138")
                    gouxuan = chrome.find_element(
                        By.XPATH, "/html/body/div/div/div[1]/div[1]/section/main/div[2]/div[2]/div[2]/div/div/form/div[5]/div/div/div/div/i")
                    gouxuan.click()
                    denglu = chrome.find_element(
                        By.XPATH, "/html/body/div/div/div[1]/div[1]/section/main/div[2]/div[2]/div[2]/div/div/form/div[4]/div/button")
                    denglu.click()
                    time.sleep(3)
                    phone_code = chrome.find_element(
                        By.XPATH, '//*[@id = "bind-mobile-form__mobile"]/div/div/div/form/p_input-sms/div/div/button')

                    phone_code.click()
                    user_input = input("请输入一些文本: ")
                    try:
                        number = int(user_input)
                        phone_code_Input = chrome.find_element(
                            By.XPATH, '/html/body/section/main/div/div/section/main/div/div[1]/div/div/div/div/form/p_input-sms/div/p_input/div/input')
                        phone_code_Input.send_keys(number)
                        print("你输入的数字是:", number)
                    except ValueError:
                        print("输入的不是有效的整数！")

                    ljyanzhen = chrome.find_element(
                        By.XPATH, '//*[@id="bind-mobile-form__mobile"]/div/div/div/p_submit/div/button')
                    ljyanzhen.click()

                def goPageZhiLian():
                    print("元素未找到，已调用处理函数")
                    page_html = chrome.page_source
                    soup1 = BeautifulSoup(page_html, 'lxml')
                    tree1 = etree.HTML(str(soup1))
                    time.sleep(1)
                    elements = tree1.xpath(
                        '/html/body/div[4]/div/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[3]/div[1]/div/div[2]')
                    userPhone = ''
                    userEmail = ''
                    if elements:
                        element_by_xpath = elements[0]
                        text_content = element_by_xpath.text if element_by_xpath.text else element_by_xpath.text_content.strip()
                        print('手机号:', text_content)
                        userPhone = text_content
                    else:
                        print("没有找到匹配的元素")
                    youxiang = tree1.xpath(
                        '/html/body/div[4]/div/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[3]/div[2]/div/span')
                    if youxiang:
                        element_by_xpath = youxiang[0]
                        text_content = element_by_xpath.text if element_by_xpath.text else element_by_xpath.text_content.strip()
                        print('邮箱:', text_content)
                        userEmail = text_content
                    else:
                        print("没有找到匹配的元素")
                    return {'userName': userPhone, 'userEmail': userEmail}
                try:
                    # 尝试查找并点击元素
                    gozhilian()
                    goPageZhiLian()
                    return goPageZhiLian()
                    # print("元素找到并点击成功")
                except NoSuchElementException:
                    return goPageZhiLian()

            chrome.quit()
            
app = Flask(__name__)
@app.route('/getEmailData', methods=['GET'])
def get_data():
    data = getEmailCreat()
    # 这里只是示例，实际中你可能需要从数据库或其他数据源获取数据
    # data = {'phoneNum': userPhone,
    #         'userEmail': userEmail}
    return jsonify(data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5050, debug=True)
